package com.example.shiro_realy.config;

import com.example.shiro_realy.domian.Permission;
import com.example.shiro_realy.domian.Role;
import com.example.shiro_realy.domian.User;
import com.example.shiro_realy.service.UserSevice;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserSevice userSevice;

    /**
     * 用户登录得时候会调用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证 doGetAuthenticationInfo");
        //从token中获取用户信息，token表示用户输入的信息
        String username =(String) authenticationToken.getPrincipal();
        //通过用户名查询用户信息
        User user = userSevice.findAllUserInfoByUsername(username);
        //通过用户名查找密码并判断
        String password = user.getPassword();
        if (password == null || "".equals(password)) {
            return null;
        }

        return new SimpleAuthenticationInfo(username,user.getPassword(),this.getClass().getName());
    }

    /**
     * 进行权限校验得时候调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权 doGetAuthorizationInfo");
        //通过principalCollection获取用户名
        String username =(String) principalCollection.getPrimaryPrincipal();
        //通过用户名向数据查询用户信息
        User user = userSevice.findAllUserInfoByUsername(username);
        List<String> stringRoleList = new ArrayList<>();
        List<String> stringPermissionList = new ArrayList<>();
        List<Role> roleList = user.getRoleList();
        for (Role role: roleList) {
            stringRoleList.add(role.getName());
            List<Permission> permissionList = role.getPermissionList();
            for (Permission permission :permissionList) {
                if (permission != null) {
                    stringPermissionList.add(permission.getName());
                }
            }
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(stringRoleList);
        authorizationInfo.addStringPermissions(stringPermissionList);

        return authorizationInfo;
    }
}
